﻿using Microsoft.AspNetCore.Mvc;

namespace LeetCode.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CharacterController : ControllerBase
    {

        [HttpPost]
        public bool IsValid(string s)
        {
            if (s.Length % 2 == 1)
            {
                return false;
            }
            Stack<char> stackLeft = new();
            foreach (var item in s)
            {
                //'('，')'，'{'，'}'，'['，']'
                if (item.Equals('(') || item.Equals('{') || item.Equals('['))
                {
                    stackLeft.Push(item);
                }
                else
                {
                    if (stackLeft.Count > 0 && stackLeft.Peek() == LeftOf(item))
                    {
                        stackLeft.Pop();
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return stackLeft.Count == 0;
        }

        private static char LeftOf(char c) => c switch
        {
            '}' => '{',
            ']' => '[',
            ')' => '(',
            _ => c,
        };

    }
}
